package LinkedListSeries;

public class IsPalindromeSolution_hot100_234 {
    public boolean isPalindrome(ListNode head) {
        if (head == null) return true;
        // 找到前一半的尾节点和后一半的头节点
        ListNode endOfFirstHalfNode = endOfFirstHalf(head);
        ListNode startOfSecondHalfNode = reverseLinkedList(endOfFirstHalfNode.next);

        ListNode firstHalf = head;
        ListNode secondHalf = startOfSecondHalfNode;
        boolean result = true;
        while (result && secondHalf != null) {
            if (firstHalf.val != secondHalf.val) {
                result = false;
            }
            firstHalf = firstHalf.next;
            secondHalf = secondHalf.next;
        }

        // 还原反转后一半链表
        endOfFirstHalfNode.next = reverseLinkedList(startOfSecondHalfNode);
        return result;
    }

    // 找到前一半的尾节点和后一半的头节点
    // 快慢指针
    public ListNode endOfFirstHalf(ListNode node) {
        ListNode slow = node;
        ListNode fast = node;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public ListNode reverseLinkedList(ListNode node) {
        ListNode prev = null;
        ListNode cur = node;

        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }
}
